package oh.june.keepscreenonwatch;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.widget.TextView;

public class DigitalClock extends TextView {

	private String mText = "";
	private Runnable mTicker;
	private Handler mHandler;
	
	private boolean mTickerStopped = false;
	private boolean mColonShow = false;
	private float mChildRatioH = 1.0f;
	
	public DigitalClock(Context context) {
		super(context);
		initClock(context);
	}

	public DigitalClock(Context context, AttributeSet attrs) {
		super(context, attrs);
		initClock(context);
	}

	private void initClock(Context context) {
		this.setIncludeFontPadding(false);
	}
	
	public void setRatio(float childRatioH){
		mChildRatioH = childRatioH;
	}
	
	@Override
	protected void onAttachedToWindow() {
		mTickerStopped = false;
		super.onAttachedToWindow();
		mHandler = new Handler();

		/**
		 * requests a tick on the next hard-second boundary
		 */
		 mTicker = new Runnable() {
			 public void run() {
				 if (mTickerStopped) 
					 return;
				 mColonShow = !mColonShow;
				 SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
				 mText = sdf.format(new Date());
				 invalidate();
				 long now = SystemClock.uptimeMillis();
				 long next = now + (500 - now % 500);
				 mHandler.postAtTime(mTicker, next);
			 }
		 };
		 mTicker.run();
	}

	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		mTickerStopped = true;
	}

	@Override
	protected void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);
		
		float textSize = 250.0f * mChildRatioH;
		
		TextPaint paint = new TextPaint();
		paint.setTextSize(textSize);
		paint.setAntiAlias(true);
		paint.setTypeface(Typeface.SANS_SERIF);
		paint.setColor(Color.YELLOW);
		
		if(mText.contains(":")){
			String hour = mText.split(":")[0];
			String dot = ":";
			String min = mText.split(":")[1];
			
			int wholeWidth = (int) paint.measureText(hour + dot + min);
			
			int xOffsetOfHour = (int)(getWidth() - wholeWidth)/2;
			int xOffsetOfDot = (int)paint.measureText(hour) + 6 + xOffsetOfHour;
			int xOffsetOfMin = (int)paint.measureText(hour + dot) + 12 + xOffsetOfHour;
			int yOffset = (int)((this.getHeight() - textSize-4)/2 + textSize);
			
			if(mColonShow){
				canvas.drawText(hour, xOffsetOfHour, yOffset, paint);
				canvas.drawText(dot, xOffsetOfDot, yOffset-20, paint);
				canvas.drawText(min, xOffsetOfMin, yOffset, paint);
			}else{
				canvas.drawText(hour, xOffsetOfHour, yOffset, paint);
				canvas.drawText(min, xOffsetOfMin, yOffset, paint);
			}
		}
		
	}

}